package pmr.core;

import java.util.Set;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.text.edits.MalformedTreeException;

import pmr.core.finder.UnusedMethodsFinder;
import pmr.core.remover.UnusedMethodRemover;
import pmr.utils.SCUtils;
import pmr.view.RemoveUnusedDialog;

public class Template {

	private ICompilationUnit compilationUnit;
	private IJavaProject javaProject;
	private ISelection selection;

	public void setUnit(ICompilationUnit compilationUnit) {
		this.compilationUnit = compilationUnit;
	}

	public void setProject(IJavaProject javaProject) {
		this.javaProject = javaProject;

	}

	public void setSelection(ISelection selection) {
		this.selection = selection;
	}

	public void findUnusedMethods(IAction action) {
		UnusedMethodsFinder unusedMethodsFinder = new UnusedMethodsFinder(
				javaProject);

		try {
			Set<IMethod> unusedMethods = unusedMethodsFinder
					.findUnusedMethods(compilationUnit);
			if (unusedMethods.isEmpty()) {
				Dialog dialog = new MessageDialog(SCUtils.getShell(), null,
						null, "No methods Found", MessageDialog.INFORMATION,
						new String[] { "ok" }, 0);
				dialog.create();
				dialog.open();
			} else {
				openRemoveDialog(unusedMethods);
			}
		} catch (Exception e) {

		}
	}

	private void openRemoveDialog(Set<IMethod> unusedMethods) {
		try {
			RemoveUnusedDialog dialog = new RemoveUnusedDialog(SCUtils
					.getShell(), unusedMethods);
			boolean removeUnused = dialog.open() == 0;
			if (!removeUnused) {
				return;
			}
			new UnusedMethodRemover(compilationUnit).remove(dialog
					.getMethodsToRemove());
		} catch (JavaModelException e) {
			e.printStackTrace();
		} catch (MalformedTreeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadLocationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
